package com.johanChan.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.johanChan.entity.User;
import com.johanChan.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @ResponseBody
    @RequestMapping("loginInfo/LoginReq")
    public String loginReq(@RequestBody String param, HttpServletRequest request) {
        System.out.println(param);
        String token = System.currentTimeMillis() + "";

        JSONObject json = new JSONObject();
        User user = JSON.parseObject(param,User.class);
        if (StringUtils.isEmpty(user.getLoginName()) || StringUtils.isEmpty(user.getPassword())){
            json.put("flag",1);
            json.put("msg","用户名或密码错误");
            return json.toString();
        }

        String userName = user.getLoginName();
        String passWord = user.getPassword();
        boolean bool =userService.login(userName,passWord);
        if (bool){
            json.put("flag",0);
            json.put("msg","登陆成功");
            json.put("token",token);
            request.getSession().setAttribute("session_user",user);//登录成功后将用户放入session中，用于拦截
        }else{
            json.put("flag",1);
            json.put("msg","用户名或密码错误");
        }
        return json.toString();
    }

    //注册操作
    @RequestMapping("/loginInfo/register")
    public String register(User user){
        int su = userService.register(user);
        if(su==0){
            System.out.println("----");
        }
        return "welcome";
    }

    //退出登录
    @RequestMapping("/outUser")
    public void outUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().removeAttribute("session_user");
        response.sendRedirect("/index");
    }



    @ResponseBody
//    @RequestMapping("/getChildren/{id}")
    public String getChildren(@PathVariable("id") Integer id) {
        String result = "";
        return result;
    }

}
